// pages/2411Ayiliao-pages/patient/patient-detail.js
Page({
  data: {
    patientInfo: {}
  },

  onLoad(options) {
    console.log('患者详情页面参数:', options)
    
    // 从页面参数获取患者信息
    const patientInfo = {
      id: options.id,
      name: options.name,
      relationship: options.relationship,
      idCard: options.idCard,
      phone: options.phone,
      isDefault: options.isDefault === 'true'
    }
    
    this.setData({
      patientInfo: patientInfo
    })
  },

  // 编辑患者
  editPatient() {
    const patient = this.data.patientInfo
    wx.navigateTo({
      url: `/pages/2411Ayiliao-pages/patient/add-patient?id=${patient.id}&name=${patient.name}&relationship=${patient.relationship}&idCard=${patient.idCard}&phone=${patient.phone}&isDefault=${patient.isDefault}`
    })
  },

  // 删除患者
  deletePatient() {
    const patient = this.data.patientInfo
    wx.showModal({
      title: '确认删除',
      content: `确定要删除就诊人"${patient.name}"吗？`,
      success: (res) => {
        if (res.confirm) {
          this.deletePatientFromServer(patient.id)
        }
      }
    })
  },

  // 设置默认患者
  setDefaultPatient() {
    const patient = this.data.patientInfo
    wx.showModal({
      title: '确认设置',
      content: `确定要将"${patient.name}"设为默认就诊人吗？`,
      success: (res) => {
        if (res.confirm) {
          this.setDefaultPatientOnServer(patient.id)
        }
      }
    })
  },

  // 从服务器设置默认患者
  setDefaultPatientOnServer(patientId) {
    console.log('开始设置默认患者，ID:', patientId)
    
    wx.showLoading({
      title: '设置中...'
    })
    
    // 尝试多种可能的API路径和方法
    const apiConfigs = [
      { url: `http://localhost:8080/patient/setDefault/${patientId}`, method: 'POST' },
      { url: `http://localhost:8080/patient/setDefault/${patientId}`, method: 'PUT' },
      { url: `http://localhost:8080/patient/setDefault/${patientId}`, method: 'PATCH' },
      { url: `http://localhost:8080/patient/${patientId}/setDefault`, method: 'POST' },
      { url: `http://localhost:8080/patient/${patientId}/setDefault`, method: 'PUT' },
      { url: `http://localhost:8080/patient/${patientId}/setDefault`, method: 'PATCH' },
      { url: `http://localhost:8080/patients/setDefault/${patientId}`, method: 'POST' },
      { url: `http://localhost:8080/patients/setDefault/${patientId}`, method: 'PUT' },
      { url: `http://localhost:8080/patients/${patientId}/setDefault`, method: 'POST' },
      { url: `http://localhost:8080/patients/${patientId}/setDefault`, method: 'PUT' },
      { url: `http://localhost:8080/api/patient/setDefault/${patientId}`, method: 'POST' },
      { url: `http://localhost:8080/api/patient/setDefault/${patientId}`, method: 'PUT' },
      { url: `http://localhost:8080/api/patient/${patientId}/setDefault`, method: 'POST' },
      { url: `http://localhost:8080/api/patient/${patientId}/setDefault`, method: 'PUT' }
    ]
    
    let currentIndex = 0
    
    const trySetDefault = () => {
      if (currentIndex >= apiConfigs.length) {
        wx.hideLoading()
        wx.showToast({
          title: '设置失败：API路径不存在',
          icon: 'none'
        })
        return
      }
      
      const config = apiConfigs[currentIndex]
      console.log(`尝试设置默认API: ${config.method} ${config.url}`)
      
      wx.request({
        url: config.url,
        method: config.method,
        header: {
          'Content-Type': 'application/json'
        },
        data: {
          patientId: patientId,
          isDefault: true
        },
        success: (res) => {
          console.log('设置默认响应:', res)
          wx.hideLoading()
          
          if (res.statusCode === 200 || res.statusCode === 201) {
            wx.showToast({
              title: '设置成功',
              icon: 'success'
            })
            // 更新本地数据
            this.setData({
              'patientInfo.isDefault': true
            })
            // 返回上一页并刷新数据
            setTimeout(() => {
              wx.navigateBack()
              // 通知上一页刷新数据
              const pages = getCurrentPages()
              const prevPage = pages[pages.length - 2]
              if (prevPage && prevPage.loadPatientData) {
                prevPage.loadPatientData()
              }
            }, 1500)
          } else if (res.statusCode === 404 || res.statusCode === 405) {
            // 尝试下一个API配置
            currentIndex++
            trySetDefault()
          } else {
            console.error('设置默认失败，状态码:', res.statusCode, '响应:', res.data)
            wx.showToast({
              title: `设置失败: ${res.statusCode}`,
              icon: 'none'
            })
          }
        },
        fail: (error) => {
          console.error('设置默认患者网络请求失败:', error)
          // 尝试下一个API配置
          currentIndex++
          trySetDefault()
        }
      })
    }
    
    trySetDefault()
  },

  // 从服务器删除患者
  deletePatientFromServer(patientId) {
    console.log('开始删除患者，ID:', patientId)
    
    wx.showLoading({
      title: '删除中...'
    })
    
    // 尝试多种可能的删除API路径
    const deleteUrls = [
      `http://localhost:8080/patient/delete/${patientId}`,
      `http://localhost:8080/patient/${patientId}`,
      `http://localhost:8080/patients/delete/${patientId}`,
      `http://localhost:8080/patients/${patientId}`,
      `http://localhost:8080/api/patient/delete/${patientId}`,
      `http://localhost:8080/api/patient/${patientId}`
    ]
    
    let currentIndex = 0
    
    const tryDelete = () => {
      if (currentIndex >= deleteUrls.length) {
        wx.hideLoading()
        wx.showToast({
          title: '删除失败：API路径不存在',
          icon: 'none'
        })
        return
      }
      
      const url = deleteUrls[currentIndex]
      console.log(`尝试删除API: ${url}`)
      
      wx.request({
        url: url,
        method: 'DELETE',
        header: {
          'Content-Type': 'application/json'
        },
        success: (res) => {
          console.log('删除响应:', res)
          wx.hideLoading()
          
          if (res.statusCode === 200) {
            wx.showToast({
              title: '删除成功',
              icon: 'success'
            })
            // 返回上一页并刷新数据
            setTimeout(() => {
              wx.navigateBack()
              // 通知上一页刷新数据
              const pages = getCurrentPages()
              const prevPage = pages[pages.length - 2]
              if (prevPage && prevPage.loadPatientData) {
                prevPage.loadPatientData()
              }
            }, 1500)
          } else if (res.statusCode === 404) {
            // 尝试下一个API路径
            currentIndex++
            tryDelete()
          } else {
            console.error('删除失败，状态码:', res.statusCode, '响应:', res.data)
            wx.showToast({
              title: `删除失败: ${res.statusCode}`,
              icon: 'none'
            })
          }
        },
        fail: (error) => {
          console.error('删除患者网络请求失败:', error)
          // 尝试下一个API路径
          currentIndex++
          tryDelete()
        }
      })
    }
    
    tryDelete()
  }
}) 